//
//  ManagerAllShareCardViewController.m
//  QRMaster
//
//  Created by lc on 16/6/3.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "ManagerAllShareCardViewController.h"
#import "CommunityCardShareCell.h"
#import "RequestNetWork.h"
#import "ComTodayAndAllShareCardModel.h"
#import "CommunityOutdataCardShareCell.h"
#import "ManagerTodayShareCardInfoVC.h"
#import "ChineseInclude.h"
#import "ZYPinYinSearch.h"
#import "MJRefresh.h"
#import "CommunityListInfo.h"
#import "CommunityListModel.h"
@interface ManagerAllShareCardViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>

@property (nonatomic,strong) UIButton * todayBtn;
@property (nonatomic,strong) UISearchBar * shareCardSearchBar;
@property (nonatomic,strong) UITableView * cardShareTableView;
@property (nonatomic,strong) NSMutableArray * cardShareArray;
@property (nonatomic,strong) NSMutableArray * totalArray;
@property (nonatomic,strong) NSMutableArray * searchArray;
@property (nonatomic,assign) NSInteger pageIndex;
@property (nonatomic,assign) NSInteger totalPageIndex;
@property (nonatomic,strong) UIAlertView * effectiveAlert;
@property (nonatomic,strong) UIAlertView * delegateAlert;
@property (nonatomic,strong) ComTodayAndAllShareCardModel * handleModel;
@property (nonatomic,strong) UIImageView * promtBackView;

@end

@implementation ManagerAllShareCardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColorFromRGB(0xebebeb);
    self.navigationItem.title = @"分享记录";
    _cardShareArray = [NSMutableArray array];
    _totalArray = [NSMutableArray array];
    _searchArray = [NSMutableArray array];
    _pageIndex = 1;
    _totalPageIndex = 1;
    [self prepareData];
    [self prepareNaviBar];
    [self prepareSearchBar];
    [self prepareTableView];
    [self preparePromtView];
    
    //获得通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(lookCell:) name:@"cellnot" object:@"CommunityAllShareCard"];

}

-(void)viewWillAppear:(BOOL)animated{
    _todayBtn.hidden = NO;
    [self prepareData];

}

-(void)viewWillDisappear:(BOOL)animated{
    _todayBtn.hidden = YES;
}

- (void)prepareData{
    if ([self IsHaveNetwork]) {
        [_cardShareTableView.mj_footer endRefreshing];
        [_cardShareTableView.mj_header endRefreshing];
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:@"0" forKey:@"today"];
    [postDict setValue:[NSString stringWithFormat:@"%ld",(long)_pageIndex] forKey:@"p"];
    [postDict setValue:_communityId forKey:@"communityId"];
    [rnk initWithPath:POST(GETCOMMUNITYSHARELIST) params:postDict block:^(id downLoadData, id error) {
        [self stopWaiting];
        DDLOG(@"downLoadData=========%@",downLoadData);
        NSDictionary * data = [downLoadData objectForKey:@"data"];
        
        if (data != nil) {
            
            if (_pageIndex == 1) {
                [_cardShareArray removeAllObjects];
            }
            NSDictionary * pageDict = [data objectForKey:@"page"];
            _totalPageIndex = [[pageDict objectForKey:@"total"] integerValue];
            NSArray * communityInfo = [data objectForKey:@"infos"];
            for (NSDictionary * dict in communityInfo) {
                ComTodayAndAllShareCardModel * model = [[ComTodayAndAllShareCardModel alloc]init];
                model.shareId = [dict objectForKey:@"id"];
                model.communityId = [dict objectForKey:@"communityId"];
                model.communityName = [dict objectForKey:@"communityName"];
                model.bulidingName = [dict objectForKey:@"buildName"];
                model.floorName = [dict objectForKey:@"floorName"];
                model.roomName = [dict objectForKey:@"roomName"];
                model.beginTime = [dict objectForKey:@"startTime"];
                model.endTime = [dict objectForKey:@"endTime"];
                model.status = [[dict objectForKey:@"status"]intValue];
                model.telePhone = [dict objectForKey:@"mobile"];
                model.shareCardUserName = [dict objectForKey:@"createrName"];
                model.shareCardTime = [dict objectForKey:@"addTime"];
                model.shareAreaCode = [dict objectForKey:@"areaCode"];
                model.enable = [[dict objectForKey:@"enable"]intValue];
                [_cardShareArray addObject:model];
            }
            if (_cardShareArray.count == 0) {
                _promtBackView.hidden = NO;
                [PromptInfoView showMessage:NSLocalizedString(@"noShareList", nil)];
            }
            else
            {
                _promtBackView.hidden = YES;
            }
            _totalArray = [_cardShareArray mutableCopy];
        }
        else if (error != nil) {
            
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
            
        }
        [_cardShareTableView.mj_header endRefreshing];
        [_cardShareTableView.mj_footer endRefreshing];
        [self stopWaiting];
        [_cardShareTableView reloadData];
        
    }];
}

- (void)postData:(NSInteger)num{
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:_communityId forKey:@"communityId"];
    [postDict setValue:_handleModel.shareId forKey:@"shareId"];
    [postDict setValue:[NSString stringWithFormat:@"%d",_handleModel.enable] forKey:@"enable"];
    [rnk initWithPath:POST(SHARECARDTOGGLE) params:postDict block:^(id downLoadData, id error) {
        if (error) {
            DDLOG(@"禁用和启用error = %@",error);
        }else{
            DDLOG(@"禁用和启用 = %@",downLoadData);
        }
    }];
}

-(void)preparePromtView
{

    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeight;
    _promtBackView = [[UIImageView alloc]initWithFrame:CGRectMake(x,y, width, height)];
    _promtBackView.backgroundColor = UIColorFromRGB(0xebebeb);
    _promtBackView.userInteractionEnabled = YES;
    _promtBackView.hidden = YES;
    [self.view addSubview:_promtBackView];
    UITapGestureRecognizer * imgViewTap  = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backViewClick:)];
    [_promtBackView addGestureRecognizer:imgViewTap];
    
    x = 0;
    width = ScreenWidth;
    y = ScreenHeight / 2.0 - 10;
    height = 20;
    UILabel * promtLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    promtLabel.text = NSLocalizedString(@"clickRefresh", nil);
    
    promtLabel.textColor = RGBA(143, 147, 148, 1);
    promtLabel.textAlignment = NSTextAlignmentCenter;
    [_promtBackView addSubview:promtLabel];

    
}

-(void)backViewClick:(UITapGestureRecognizer *)tap
{
    _promtBackView.hidden = YES;
    [self prepareData];
}

- (void)prepareSearchBar{
    _shareCardSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 45)];
    _shareCardSearchBar.placeholder = @"搜索分享人、分享时间";
    _shareCardSearchBar.backgroundColor = UIColorFromRGB(0xebebeb);
    _shareCardSearchBar.barStyle = UIBarStyleDefault;
    _shareCardSearchBar.delegate = self;
    [self.view addSubview:_shareCardSearchBar];
}

- (void)prepareTableView{
    _cardShareTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 45, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT-64-45)];
    _cardShareTableView.dataSource = self;
    _cardShareTableView.delegate = self;
    _cardShareTableView.backgroundColor = UIColorFromRGB(0xebebeb);
    [self.view addSubview:_cardShareTableView];
    
    UIView * headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 0.5)];
    headerView.backgroundColor = UIColorFromRGB(0xc1c1c1);
    _cardShareTableView.tableHeaderView = headerView;
    UIView * footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 0.5)];
    footerView.backgroundColor = UIColorFromRGB(0xc1c1c1);
    _cardShareTableView.tableFooterView = footerView;
    
    __weak ManagerAllShareCardViewController * weakSelf = self;
    [_cardShareTableView.mj_header beginRefreshing];
    _cardShareTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _pageIndex = 1;
        [weakSelf prepareData];
    }];
    [_cardShareTableView.mj_footer beginRefreshing];
    _cardShareTableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        if (_pageIndex >= _totalPageIndex) {
            [PromptInfoView showMessage:NSLocalizedString(@"noMoreShareInfo", nil)];
            [_cardShareTableView.mj_footer endRefreshing];
        }
        else
        {
            _pageIndex ++;
            [self prepareData];
        }
        
    }];

}



- (void)prepareNaviBar{
    _todayBtn = [[UIButton alloc] initWithFrame:CGRectMake(UI_SCREEN_WIDTH-16-60, 14, 60, 16)];
    _todayBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [_todayBtn setTitle:@"今天" forState:UIControlStateNormal];
    [_todayBtn setTitleColor:UIColorFromRGB(0x7dc234) forState:UIControlStateNormal];
    _todayBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [_todayBtn addTarget:self action:@selector(todayBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:_todayBtn];
}

#pragma mark  not method
/**
 *  通知方法
 */
- (void)lookCell:(NSNotification *)user{
    
    NSDictionary *dic = user.userInfo;
    NSInteger index = [dic[@"cellindex"] integerValue];
    ManagerTodayShareCardInfoVC * shareCardInfoVC = [[ManagerTodayShareCardInfoVC alloc] init];
    shareCardInfoVC.dataModel = _cardShareArray[index];
    [self.navigationController pushViewController:shareCardInfoVC animated:YES];
    
}

- (void)TagTableView{
    
    //获取所有的单元格,便利判断
    NSArray *array = _cardShareTableView.visibleCells;
    for (CommunityCardShareCell *cell in array) {
        //判断
        if (cell.showView.contentOffset.x != 0) {
            [UIView animateWithDuration:0.1 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                [cell.showView setContentOffset:CGPointMake(0, 0)];
            } completion:nil];
        }
    }
    
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _cardShareArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    _handleModel = _cardShareArray[indexPath.row];
    if (_handleModel.status==1) {
        static NSString * ID = @"cardShareCell";
        CommunityCardShareCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (!cell) {
            cell = [[CommunityCardShareCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        cell.isTodayShareCard = NO;
        [cell setCellWithModel:_handleModel];
//        for (CommunityListModel * comModel in _comListArray) {
//            if ([comModel.communityId isEqualToString:_handleModel.communityId]) {
//                if ([_handleModel.shareAreaCode isEqualToString:comModel.areaCodeString]) {
//                    cell.mobileLabel.text = _handleModel.telePhone;
//                }
//                else
//                {
//                    cell.mobileLabel.text = [NSString stringWithFormat:@"+%@ %@",_handleModel.shareAreaCode,_handleModel.telePhone];
//                }
//            }
//        }
        cell.effectiveBtn.tag = indexPath.row;
        cell.deleteBtn.tag = indexPath.row;
        cell.showView.tag = indexPath.row;
        //有效
        cell.effectiveBlock = ^(NSInteger index){
            _handleModel = _cardShareArray[index];
            if (_handleModel.enable) {
                _effectiveAlert = [[UIAlertView alloc] initWithTitle:@"使分享记录暂时失效" message:@"房卡失效后，接受者将被禁止使用该房卡，直到重新启用" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"失效", nil];
                _effectiveAlert.tag = 101;
                [_effectiveAlert show];
            }else{
                _handleModel.enable = !_handleModel.enable;
                [self postData:_handleModel.enable];
                [_cardShareTableView reloadData];
            }

        };
        //删除
        cell.deleteBlock = ^(NSInteger index){
            _handleModel = _cardShareArray[index];
            _delegateAlert = [[UIAlertView alloc] initWithTitle:@"删除分享记录" message:@"将分享记录删除，接收者将无法使用该放卡" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"删除", nil];
            _delegateAlert.tag = 102;
            [_delegateAlert show];
            
        };
        return cell;

    }else{
        static NSString * ID = @"outDataCardShareCell";
        CommunityOutdataCardShareCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (!cell) {
            cell = [[CommunityOutdataCardShareCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        cell.isTodayShareCard = NO;
        [cell setCellWithModel:_handleModel];
        cell.deleteBtn.tag = indexPath.row;
        cell.showView.tag = indexPath.row;
        //删除
        cell.deleteBlock = ^(NSInteger index){
            _handleModel = _cardShareArray[index];
            _delegateAlert = [[UIAlertView alloc] initWithTitle:@"删除分享记录" message:@"将分享记录删除，接收者将无法使用该放卡" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"删除", nil];
            _delegateAlert.tag = 102;
            [_delegateAlert show];
            
        };
        return cell;
    }
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 56;
}

/**
 *  让系统滑动取消
 *
 */
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

#pragma mark - UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag==101) {
        if (buttonIndex==1) {
            _handleModel.enable = !_handleModel.enable;
            [self postData:_handleModel.enable];
            [_cardShareTableView reloadData];
        }
    }else{
        if (buttonIndex==1) {
            NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
            NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
            RequestNetWork * rnk = [[RequestNetWork alloc]init];
            [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
            [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
            [postDict setValue:_handleModel.shareId forKey:@"shareId"];
            [postDict setValue:_handleModel.communityId forKey:@"communityId"];
            [rnk initWithPath:POST(DELETESHARE) params:postDict block:^(id downLoadData, id error) {
                if ([downLoadData objectForKey:@"data"] != nil)
                {
                    [_cardShareArray removeObject:_handleModel];
                    [_cardShareTableView reloadData];
                }
                else
                {
                    [PromptInfoView showMessage:[error objectForKey:@"info"]];
                }
                
            }];
            
        }
        
    }
}


#pragma mark - searchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    searchBar.showsCancelButton = YES;
    for(UIView *view in  [[[_shareCardSearchBar subviews] objectAtIndex:0] subviews]) {
        if([view isKindOfClass:[UIButton class]]) {
            UIButton * cancel =(UIButton *)view;
            [cancel setTitle:@"取消" forState:UIControlStateNormal];
            [cancel setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
    }
    
}


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{

    if (searchText.length!=0) {
        [_searchArray removeAllObjects];
        if (![ChineseInclude isIncludeChineseInString:searchText]){
            _searchArray = [NSMutableArray arrayWithArray: [ZYPinYinSearch searchWithOriginalArray:_totalArray andSearchText:searchText andSearchByPropertyName:@"shareCardUserName"]];
        }
        for (ComTodayAndAllShareCardModel * model in _totalArray) {
            if ( ([model.shareCardUserName rangeOfString:searchText].location != NSNotFound) || ([model.shareCardTime rangeOfString:searchText].location != NSNotFound) ) {
                [_searchArray addObject:model];
            }
        }
        _cardShareArray = [_searchArray mutableCopy];
    }
    if ([searchText isEqualToString:@""]) {
        _cardShareArray = _totalArray;
    }
    [_cardShareTableView reloadData];
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    searchBar.text = @"";
    [searchBar resignFirstResponder];
    searchBar.showsCancelButton = NO;
    _cardShareArray = [_totalArray mutableCopy];
    [_cardShareTableView reloadData];
}

#pragma mark - 今天按钮点击
- (void)todayBtnClick{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
